<template>
  <d2-container>
  <section class="vue-monitor">
    <el-row>
      <el-col :span="5" class="monitor-d monitor-tree-d">
        <el-scrollbar :style="'height:100%;width: 100%'">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19" class="monitor-d" style="padding-left:10px">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">

              <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="small">
                <el-option
                  v-for="(item, index) in meterTypeList" :key="index"
                  :label="item.paramValue"
                  :value="item.paramKey">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="el-form-item--mini" label="日期: ">
              <el-select v-model="dataForm.dateType" placeholder="请选择"  size="small" style="width: 80px;">
                <el-option
                  v-for="(item, index) in Config.searchDate" :key="index"
                  :label="item.label"
                  :value="item.date">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item  label-width="40px" class="el-form-item--mini">
              <el-date-picker
                v-model="dataForm.date"
                placeholder="时间"
                style="width: 200px;"
                class="filter-item"
                size="small"
                :picker-options="pickerOptions"
                :type="dataForm.dateType"
                suffix-icon="el-icon-date"
                clearable
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item class="el-form-item--mini">
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="getPowerDataList"
              >查询</el-button>
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-download"
                size="small"
                @click="exoprtData"
              >导出</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-table
            :data="meterdataList"
            border
            v-loading="dataListLoading"
            style="width: 100%;overflow:visible;"
          >
            <el-table-column
              prop="bName"  fixed  width="180"
              header-align="center"
              align="center"
              label="区域名称"
            >
              <template
                slot-scope="scope"
              ><span style="color: rgb(230, 162, 60)">{{scope.row.bName}}</span>
              </template>
            </el-table-column>
            <el-table-column :label="item.lable" v-for="item in timelabel" :key="item.value">
              <el-table-column
                prop="currentValue"  width="150"
                header-align="left"
                align="center"
                label="费用(¥)"
              >
                <template
                  slot-scope="scope"  width="150"
                ><span style="color: rgb(230, 162, 60)">{{scope.row.fee[item.value]}}</span>
                </template>

              </el-table-column>
              <el-table-column
                prop="currentValue" width="150"
                header-align="left"
                align="center"
                :label="'用能('+currentUnit+')'"
              >
                <template
                  slot-scope="scope"
                >{{scope.row.val[item.value]}}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="合计">
              <el-table-column
                prop="currentValue"  width="150"
                header-align="left"
                align="center"
                label="费用(¥)"
              >
                <template
                  slot-scope="scope"
                ><span style="color: rgb(230, 162, 60)">{{scope.row.totalFee}}</span>
                </template>

              </el-table-column>
              <el-table-column
                prop="currentValue"  width="150"
                header-align="left"
                align="center"
                :label="'用能('+currentUnit+')'"
              >
                <template
                  slot-scope="scope"
                >{{scope.row.totalVal}}
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </section>
  </d2-container>
</template>
<script>
import areaTree from './compont/area_tree';
import * as Util from "@/utils";
import Config from "@/utils/config"
export default {
  /*
  * 费用报表
  **/
  data() {
    return {
      timelabel:[],
      time:{
        date:[{"lable":"00:00","value":"00"},{"lable":"01:00","value":"01"},{"lable":"02:00","value":"02"},{"lable":"03:00","value":"03"},{"lable":"04:00","value":"04"},{"lable":"05:00","value":"05"},{"lable":"06:00","value":"06"},{"lable":"07:00","value":"07"},{"lable":"08:00","value":"08"},{"lable":"09:00","value":"09"},{"lable":"10:00","value":"10"},{"lable":"11:00","value":"11"},
             {"lable":"12:00","value":"12"},{"lable":"13:00","value":"13"},{"lable":"14:00","value":"14"},{"lable":"15:00","value":"15"},{"lable":"16:00","value":"16"},{"lable":"17:00","value":"17"},{"lable":"18:00","value":"18"},{"lable":"19:00","value":"19"},{"lable":"20:00","value":"20"},{"lable":"21:00","value":"21"},{"lable":"22:00","value":"22"},{"lable":"23:00","value":"23"}],
        month:[{"lable":"01","value":"01"},{"lable":"02","value":"02"},{"lable":"03","value":"03"},{"lable":"04","value":"04"},{"lable":"05","value":"05"},{"lable":"06","value":"06"},{"lable":"07","value":"07"},{"lable":"08","value":"08"},{"lable":"09","value":"09"},{"lable":"10","value":"10"},{"lable":"11","value":"11"},
                {"lable":"12","value":"12"},{"lable":"13","value":"13"},{"lable":"14","value":"14"},{"lable":"15","value":"15"},{"lable":"16","value":"16"},{"lable":"17","value":"17"},{"lable":"18","value":"18"},{"lable":"19","value":"19"},{"lable":"20","value":"20"},{"lable":"21","value":"21"},{"lable":"22","value":"22"},{"lable":"23","value":"23"},
                {"lable":"24","value":"24"},{"lable":"25","value":"25"},{"lable":"26","value":"26"},{"lable":"27","value":"27"},{"lable":"28","value":"28"},{"lable":"29","value":"29"},{"lable":"30","value":"30"},{"lable":"31","value":"31"}],
        year:[{"lable":"01","value":"01"},{"lable":"02","value":"02"},{"lable":"03","value":"03"},{"lable":"04","value":"04"},{"lable":"05","value":"05"},{"lable":"06","value":"06"},{"lable":"07","value":"07"},{"lable":"08","value":"08"},{"lable":"09","value":"09"},{"lable":"10","value":"10"},{"lable":"11","value":"11"},{"lable":"12","value":"12"}]
      },
      meterdataList:[],
      buildList:'',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      Config:Config,
      meterTypeList:[],
      dataForm: {
        date: new Date(),
        dateType:'',
        energyType:'',
        subEnergyType:'',//分项选择值
      },
      currentUnit:'',
      dataListLoading:false,
    }
  },
  components:{
    areaTree
  },
  computed:{
    containerHeight() {
      return Util.getClientHeight() - 143;
    }
  },
  watch: {
    'dataForm.energyType':function(newV,oldV){
      this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  },
  methods: {
    formarDate(type, date) {
      return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
    },
    /**
     * 查询数据
     * */
    getPowerDataList() {
      if( this.dataForm.energyType =='' || this.buildList =='') {
        return
      }
      this.dataListLoading = true;
      this.meterdataList = []
      this.changeDateType()
      this.$api.okhttp({
        url:this.$http.adornUrl('/eas/dmyReport/list'),
        method: "post",
        data: this.$http.adornParams(
          {
            buildingIds: this.buildList,
            date: (this.dataForm.date&&this.dataForm.date!="")? this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)): '',
            dateType: Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,
            meterType: this.dataForm.energyType,
            customerId: this.$util.cookies.get("customer_id"),
            projectId:this.$util.cookies.get("cuuren_projectId")
          }
        )
      }).then((data) => {
        if (data && data.code === 0) {
            this.meterdataList = data.data;
        }
        this.dataListLoading = false;
      })

    },
    getDateStr(){
      return (this.dataForm.date&&this.dataForm.date!="")?this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):''
    },
    formarDate(type, date) {
      return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
    },
    exoprtData(){
      // 导出数据
      let headerDay=['区域名称','当日用能('+this.currentUnit+')','昨日用能('+this.currentUnit+')','增加值('+this.currentUnit+')','环比(%)'];
      let headerMonth=['区域名称','当月用能('+this.currentUnit+')','上月用能('+this.currentUnit+')','增加值('+this.currentUnit+')','环比(%)'];
      let props=['bName','totalVal','totalFee']
      let fileName=`费用报表(${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue})${this.getDateStr()}统计`
      let header = headerDay
      if(this.dataForm.dateType==='month'){
        header = headerMonth
      }
      let header1=["区域名称"]
      let header2=[""]

      this.timelabel.forEach(ele=>{
        header1.push(ele.lable)
        header1.push("")
        header2.push("费用(¥)")
        header2.push('用能('+this.currentUnit+')')

      })
      header1.push("合计")
      header1.push("")
      header2.push("费用(¥)")
      header2.push('用能('+this.currentUnit+')')
      let dataList = []
      this.meterdataList.forEach(e=>{
          let bList = [e.bName]
          this.timelabel.forEach(ele=>{
            bList.push(e.fee[ele.value])
            bList.push(e.val[ele.value])
          })
        bList.push(e.totalFee)
        bList.push(e.totalVal)
        dataList.push(bList)
      })
      //合并单元格
      let merges = [
        "A1:A2","B1:C1","D1:E1","F1:G1","H1:I1","J1:K1","L1:M1","N1:O1","P1:Q1","R1:S1","T1:U1","V1:W1","X1:Y1","Z1:AA1","AB1:AC1",
        "AD1:AE1","AF1:AG1","AH1:AI1","AJ1:AK1","AL1:AM1","AN1:AO1","AP1:AQ1","AR1:AS1","AT1:AU1","AV1:AW1","AX1:AY1","AZ1:BA1","BB1:BC1",
        "BD1:BE1","BF1:BG1","BH1:BI1"
      ];
      merges = merges.slice(0, this.timelabel.length+2)

      this.export2Excel(header1,header2,props,fileName,dataList,merges);
    },
    export2Excel(tHeader1, tHeader2,fi, fiNa, dataList,merges) {
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const { export_json_to_excel,export_json_to_excel_mutiHeader } = require('@/utils/Export2Excel.js')
       // const list = JSON.parse(JSON.stringify(this.meterdataList));
        // let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        //   return total + currentValue.val;
        // }, 0);
        // list.push({
        //   "buildingName":'合计',
        //   "val":sumVal
        // })
       // const data = this.formatJson(filterVal, list)
        export_json_to_excel_mutiHeader({ multiHeader: tHeader1, multiHeader2: tHeader2, data:dataList, filename: fileName, merges })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeDateType() {
      if (this.dataForm.dateType === 'date') {
        this.timelabel = this.time.date
      } else if (this.dataForm.dateType === 'month') {
        let nowDate = new Date(this.dataForm.date);
        let days = new Date(nowDate.getFullYear(), nowDate.getMonth()+ 1, 0).getDate()
        this.timelabel = this.time.month.slice(0,days)
      }else if (this.dataForm.dateType === 'year') {
        this.timelabel = this.time.year
      }
    },
    treeNodeChange(data){
      this.buildList = data
      this.getPowerDataList()
    },
    queryStatic(type,paramValue,callback) {
      let params = {
        'code': type ,
        "customerId":this.$util.cookies.get('customer_id')
      }
      if(paramValue){
        Object.assign(params,{paramValue,paramValue});
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },

  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 163;
    },
    bottomChartHeight(){
      return Util.getClientHeight() - 298;
    }
  },
  created() {
    this.dataForm.dateType=Config.searchDate[0].date;
    this.timelabel = this.time[this.dataForm.dateType]
    this.$nextTick(()=>{
      this.queryStatic("METER_TYPE",null,data=>{
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.currentUnit = data.page[0].paramExt;
        } else {
          this.meterTypeList = []
        }
        this.getPowerDataList()
      });
    })
  }
}

</script>
<style scoped lang="scss">
  @import "../../assets/scss/_variables";
.vue-monitor {
  min-width: 900px;
}

.vue-monitor .el-row {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
.vue-monitor .monitor-d{
  // box-shadow: 0px 0px 1px 1px #f7f6f6;
}
.vue-monitor .monitor-tree-d {
    /*position: absolute;*/
    height: 100%;
    top: 0;
    /*right: 0;*/
}




/*清除浮动代码*/

.clearfloat:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0
}

.clearfloat {
  zoom: 1
}


</style>
